package com.lntea.netty.im.handler;

import com.lntea.netty.im.packet.MessageRequestPacket;
import com.lntea.netty.im.packet.MessageResponsePacket;
import com.lntea.netty.im.packet.common.Session;
import com.lntea.netty.im.packet.common.SessionUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Date;

/**
 * 消息请求处理Handler
 */
public class MessageRequestHandler extends SimpleChannelInboundHandler<MessageRequestPacket> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageRequestPacket reqPacket) throws Exception {
        String toUserId = reqPacket.getToUserId();
        System.out.println(new Date() + String.format(": 收到客户端消息：接收人:%s,消息:%s", toUserId
                , reqPacket.getMessage()));

        // 当前用户会话
        Session session = SessionUtil.getSession(ctx.channel());

        // 组装响应消息
        MessageResponsePacket respPacket = new MessageResponsePacket(session.getUserId(), session.getUserName());
        respPacket.setMessage(reqPacket.getMessage());

        // 获取要发送的用户Channel
        Channel toUserChannel = SessionUtil.getChannel(toUserId);
        if (toUserChannel != null && SessionUtil.hasLogin(toUserChannel)) {
            // 发送消息
            toUserChannel.writeAndFlush(respPacket);
        } else {
            System.out.println(String.format("用户%s不在线，发送消息失败", toUserId));
        }
    }
}
